package cn.car91.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html.ImageGetter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.adapter.CommentListAdapter;
import cn.car91.adapter.HardwareListAdapter;
import cn.car91.adapter.TechnologyListAdapter;
import cn.car91.bean.Hardware;
import cn.car91.bean.RepairShop;
import cn.car91.bean.RepairShopComment;
import cn.car91.bean.Service;
import cn.car91.bean.Technology;
import cn.car91.bean.User;
import cn.car91.http.HttpHandler;
import cn.car91.pager.CommentPager;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.ImageManager;
import cn.car91.utils.MobileOperationUtil;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;
import cn.car91.view.MyProgressDialog;
import cn.car91.view.VerticalScrollView;
import cn.car91.view.WordWrapView;
import cn.car91.view.XListView;
import cn.car91.view.XListView.IXListViewListener;
import cn.car91.view.XListViewFooter;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnRadioGroupCheckedChange;

public class RepairShopDetailActivity extends BaseActivity {
  final static int Request_Code = 20001;
  boolean hadCollection = false;

  private CommentPager commentPager = new CommentPager();

  // 详情页面参数
  String rid = null;
  String rname = null;
  List<ImageView> imageViews;
  /*@ViewInject(R.id.repairshop_detail_pic)
  ViewPager viewPager;*/
  @ViewInject(R.id.repairshop_detail_scroll)
  ScrollView repairShopDetailScroll;
  @ViewInject(R.id.repairshop_comment_list)
  XListView commentList;
  // @ViewInject(R.id.comment_score)
  // RadioGroup commentGroup;
  // @ViewInject(R.id.repairshop_detail_morecomment)
  // TextView moreComment;
  // @ViewInject(R.id.repairshop_detail_collection)
  // Button collectionBtn;
  @ViewInject(R.id.repairshop_detail)
  VerticalScrollView detailScrollView;
  @ViewInject(R.id.repairshop_comment)
  VerticalScrollView commentScrollView;
  @ViewInject(R.id.repairshop_detail_collection)
  Button repaircollectionBtn;
  @ViewInject(R.id.repairshop_detail_comment)
  Button repaircommentBtn;
  @ViewInject(R.id.repairshop_detail_call)
  Button repaircallBtn;
  @ViewInject(R.id.repairshop_detail_nav)
  Button repairnavBtn;
  @ViewInject(R.id.repairshop_comment_attitude)
  ProgressBar attitudeProgress;
  @ViewInject(R.id.repairshop_comment_charge)
  ProgressBar chargeProgress;
  @ViewInject(R.id.repairshop_comment_environment)
  ProgressBar environmentProgress;
  @ViewInject(R.id.repairshop_comment_technology)
  ProgressBar technologyProgress;
  @ViewInject(R.id.repairshop_comment_hardware)
  ProgressBar hardwareProgress;
  
  RepairShopDetailHandler repairShopDetailHandler;
  CollectionBtnClickEvent collectionBtnClickEvent = new CollectionBtnClickEvent();

  CommentListAdapter<RepairShopComment> commentListAdapter = null;
  TechnologyListAdapter technologyListAdapter = null;
  HardwareListAdapter hardwareListAdapter = null;

  // 初始化一个自定义的Dialog
  Dialog dialog = null;

  String score = null;
  String phoneNum;

  static ImageManager imageManager;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    setContentView(R.layout.activity_repairshop_detail);
    super.onCreate(savedInstanceState);
    imageManager = new ImageManager(RepairShopDetailActivity.this,
        "sdcard/car91/temp/repairshop");
    dialog = new MyProgressDialog(RepairShopDetailActivity.this,
        R.style.MyProgressDialog);

    rid = getIntent().getStringExtra("rid");

    initView();
    
    if (RegexUtil.isNotNull(rid)) {
      HttpHandler.httpHandler.getRepairShopDetail(rid, callbackDetail);
    }
  }

  /* 详情页面 */
  private class RepairShopDetailHandler {
    public ImageView repairShopLogo;
    // public ImageView repairShopLogo;
    public TextView repairShopName;// 商家名称
    public TextView repairShopGood;// 商家评论
    public TextView repairShopDistance;// 商家距离
    public TextView repairShopAddress;// 商家地址
    public TextView repairShopRgrade;// 商家资质
    public ImageView repairShopRank;// 商家认证等级
    public ImageView repairShopLincence;
    public WordWrapView repairShopGridLayout;
  }

  private void initView() {
    repairShopDetailHandler = new RepairShopDetailHandler();
    repairShopDetailHandler.repairShopLogo = (ImageView) findViewById(R.id.repairshop_detail_pic);
    repairShopDetailHandler.repairShopName = (TextView) findViewById(R.id.repairshop_detail_name);
    repairShopDetailHandler.repairShopGood = (TextView) findViewById(R.id.repairshop_detail_good);
    repairShopDetailHandler.repairShopDistance = (TextView) findViewById(R.id.repairshop_detail_distance);
    repairShopDetailHandler.repairShopAddress = (TextView) findViewById(R.id.repairshop_detail_address);
    repairShopDetailHandler.repairShopRgrade = (TextView) findViewById(R.id.repairshop_detail_rgrade);
    repairShopDetailHandler.repairShopRank = (ImageView) findViewById(R.id.repairshop_detail_rank);
    repairShopDetailHandler.repairShopGridLayout = (WordWrapView) findViewById(R.id.repairshop_detail_service);
    // repairShopDetailHandler.repairShopContact = (TextView)
    // findViewById(R.id.repairshop_detail_contact);
    // repairShopDetailHandler.repairShopDesc = (TextView)
    // findViewById(R.id.repairshop_detail_desc);
    // repairShopDetailHandler.repairShopLincence = (ImageView)
    // findViewById(R.id.repairshop_detail_lincence);
  }

  /**
   * 页面显示商家信息
   *
   * @param repairShop
   *          商家
   */
  private void initData(RepairShop repairShop) {
    if (repairShopDetailHandler != null && repairShop != null) {
      imageManager.displayImage(
          getCar91Application().getCenterServerUrl() + "/"
              + repairShop.getLogo(),
          repairShopDetailHandler.repairShopLogo,
          RepairShopDetailActivity.this.getResources().getDrawable(
              R.drawable.ico_launcher));
      imageManager.displayImage(
          getCar91Application().getCenterServerUrl() + "/"
              + repairShop.getDetail().getLicense(),
          repairShopDetailHandler.repairShopLincence,
          RepairShopDetailActivity.this.getResources().getDrawable(
              R.drawable.ico_launcher));

      rname = repairShop.getName();
      repairShopDetailHandler.repairShopName.setText(rname);

      try {
        Long count = repairShop.getCommentcount();
        int good = 100;
        if (cn.car91.utils.RegexUtil.isNotNull(count)) {
          good = (int) ((repairShop.getGoodcount() * 1.0 / count) * 100);
        }
        repairShopDetailHandler.repairShopGood.setText("好评率：" + good + "%");
      } catch (Exception e) {
      }

      if (repairShop.getDetail().getRank() != null
          && repairShop.getDetail().getRank() > 0) {
        repairShopDetailHandler.repairShopRank.setVisibility(View.VISIBLE);
      }

      try {
        BDLocation location = getCar91Application().getmLocationClient()
            .getLastKnownLocation();
        LatLng curLatLng = new LatLng(location.getLatitude(),
            location.getLongitude());

        String[] dtmp = repairShop.getDetail().getPosition().split(",");
        double lon = Double.valueOf(dtmp[0]);
        double lat = Double.valueOf(dtmp[1]);
        LatLng latLng = new LatLng(lat, lon);
        double distance = DistanceUtil.getDistance(curLatLng, latLng);

        if (distance > 5000) {
          repairShopDetailHandler.repairShopDistance.setText(String.format(
              "%.1f", distance / 1000) + "km");
        } else {
          int dis;
          dis = (int) distance;
          repairShopDetailHandler.repairShopDistance.setText(dis + "m");
        }
      } catch (Exception e) {
        repairShopDetailHandler.repairShopDistance.setText("");
      }

      repairShopDetailHandler.repairShopAddress.setText(repairShop.getDetail()
          .getAddress());

      if (repairShop.getDetail().getRepairgrade() != null) {
        switch (repairShop.getDetail().getRepairgrade()) {
        case 0:
          repairShopDetailHandler.repairShopRgrade.setText("资质：普通");
          break;
        case 1:
          repairShopDetailHandler.repairShopRgrade.setText("资质：一类");
          break;
        case 2:
          repairShopDetailHandler.repairShopRgrade.setText("资质：二类");
          break;
        default:
          repairShopDetailHandler.repairShopRgrade.setText("资质：三类");
          break;
        }
      }

      if (repairShop.getDetail().getServices() != null) {
        for (Service service : repairShop.getDetail().getServices()) {
          repairShopDetailHandler.repairShopGridLayout.addView(createTextView(service.getName()));
        }
      }
      /*
       * StringBuffer serviceStr = new StringBuffer(); Set<Service> services =
       * repairShop.getDetail().getServices(); if (services != null) { for
       * (Service service : services) { serviceStr.append(service.getName() +
       * " "); } }
       * 
       * repairShopDetailHandler.repairShopContent.setText(serviceStr);
       */
      /*
       * String addressHtml = "<font color='#0066cc'>&nbsp;<img src='" +
       * R.drawable.map_point_red + "'/>查看地图</font>";
       * repairShopDetailHandler.repairShopAddress.setText(repairShop
       * .getDetail().getAddress());
       * repairShopDetailHandler.repairShopAddress.append(Html.fromHtml(
       * addressHtml, imgGetter, null));
       */

      creditUrl = repairShop.getDetail().getLicense();
      descContent = repairShop.getDetail().getDesc();
      if(repairShop.getDetail().getTechnologies() != null) {
        for (Technology t : repairShop.getDetail().getTechnologies()) {
          allTechs.add(t.getName());
        }
      }
      if(repairShop.getDetail().getHardwares() != null) {
        for (Hardware t : repairShop.getDetail().getHardwares()) {
          allHards.add(t.getName());
        }
      }
      phoneNum = repairShop.getDetail().getPhone();
      /*
       * if (RegexUtil.isNotNull(phoneNum)) { String[] numbers =
       * phoneNum.split("\\s+"); if (numbers.length > 0) {
       * repairShopDetailHandler.repairShopContact .setText(numbers[0]); } }
       */

      /*
       * repairShopDetailHandler.repairShopDesc.setText(Html
       * .fromHtml(RegexUtil.htmlFilter(repairShop.getDetail() .getDesc())));
       */

      // 搜藏按钮事件
      collectionBtnClickEvent.setRid(repairShop.getId());
      /*
       * repairShopDetailHandler.repaircollectionBtn
       * .setOnClickListener(collectionBtnClickEvent.onClickListener);
       */

      // 滚动置顶
      repairShopDetailScroll.smoothScrollTo(0, 0);

      // 地图
      MapClickEvent mapClickEvent;
      try {
        mapClickEvent = new MapClickEvent(repairShop.getLon().doubleValue(),
            repairShop.getLat().doubleValue(), repairShop);
      } catch (Exception e) {
        String pointString = repairShop.getDetail().getPosition();
        String[] points = pointString.split(",");
        mapClickEvent = new MapClickEvent(Double.valueOf(points[0]),
            Double.valueOf(points[1]), repairShop);
      }

      repairnavBtn.setOnClickListener(mapClickEvent.onClickListener);
      /*
       * repairShopDetailHandler.repairShopAddress
       * .setOnClickListener(mapClickEvent.onClickListener);
       */

      // 留言栏
      // commentListAdapter = new
      // CommentListAdapter(RepairShopDetailActivity.this,
      // R.layout.view_comment_item);
      // commentList.setAdapter(commentListAdapter);
      // moreComment.setOnClickListener(onMoreCommentClickListener);

      // 技术力量栏
      // technologyListAdapter = new
      // TechnologyListAdapter(getApplicationContext());
      // techGridView.setAdapter(technologyListAdapter);
      // technologyListAdapter.setData(new
      // ArrayList<Technology>(repairShop.getDetail().getTechnologies()));
      // technologyListAdapter.notifyDataSetChanged();

      // 硬件设施栏
      // hardwareListAdapter = new
      // HardwareListAdapter(getApplicationContext());
      // hardGridView.setAdapter(hardwareListAdapter);
      // hardwareListAdapter.setData(new
      // ArrayList<Hardware>(repairShop.getDetail().getHardwares()));
      // hardwareListAdapter.notifyDataSetChanged();

      // 底部
      repaircallBtn.setOnClickListener(onCallClickListener);
      repaircommentBtn.setOnClickListener(onCommentClickListener);
      // repaircollectionBtn.setOnClickListener(oncollectionclicklistener);

      ((TextView) findViewById(R.id.header_text)).setText(repairShop.getName());

      getCommentItemGrade();
      commentListAdapter = new CommentListAdapter<RepairShopComment>(this, R.layout.view_comment_item);
      commentList.setAdapter(commentListAdapter);
      commentList.setPullLoadEnable(true);
      commentList.setPullRefreshEnable(true);
      commentList.setXListViewListener(onCommentViewListener);
      commentPager.getRepairShopComment(repairShop.getId(), score,
          callbackRefreshCommentList);

      checkCollection();
    } else {
      new HerilyAlertDialog.Builder(RepairShopDetailActivity.this)
          .setMessage("该商家被关黑屋子\n或已被删除").create().show();
    }
  }

  private TextView createTextView(String text){
      TextView textView = (TextView) LayoutInflater.from(this).inflate(R.layout.view_service_item, null);
      textView.setText(text);
      return textView;
  }
  
  @OnRadioGroupCheckedChange(R.id.repairshop_detail_radioTabs)
  public void onRepairShopCheckedChanged(RadioGroup arg0, int arg1) {
    switch (arg1) {
    case R.id.repairshop_detail_tab_detail:
      commentScrollView.setVisibility(View.GONE);
      detailScrollView.setVisibility(View.VISIBLE);
      break;
    case R.id.repairshop_detail_tab_comment:
      detailScrollView.setVisibility(View.GONE);
      commentScrollView.setVisibility(View.VISIBLE);
      break;
    default:
      break;
    }
  }

  private void getCommentItemGrade() {
    getRepairShopAllItemGrade("0", attitudeProgress);
    getRepairShopAllItemGrade("1", chargeProgress);
    getRepairShopAllItemGrade("2", environmentProgress);
    getRepairShopAllItemGrade("3", technologyProgress);
    getRepairShopAllItemGrade("4", hardwareProgress);
  }
  
  private void getRepairShopAllItemGrade(String pitem,final ProgressBar progressBar){
    HttpHandler.httpHandler.getRepairShopCommentItem(rid, pitem, new RequestCallBack() {
      @Override
      public void onFailure(HttpException arg0, String arg1) {
        LogUtils.e("the http error is "+arg0.getMessage());
      }

      @Override
      public void onSuccess(ResponseInfo arg0) {
        try {
          progressBar.setProgress(Integer.parseInt(arg0.result.toString()));
          switch (progressBar.getId()) {
          case R.id.repairshop_comment_attitude:
            ((TextView)findViewById(R.id.repairshop_comment_attitude_sum)).setText(arg0.result.toString()+"%");
            break;
          case R.id.repairshop_comment_charge:
            ((TextView)findViewById(R.id.repairshop_comment_charge_sum)).setText(arg0.result.toString()+"%");
            break;
          case R.id.repairshop_comment_environment:
            ((TextView)findViewById(R.id.repairshop_comment_environment_sum)).setText(arg0.result.toString()+"%");
            break;
          case R.id.repairshop_comment_technology:
            ((TextView)findViewById(R.id.repairshop_comment_technology_sum)).setText(arg0.result.toString()+"%");
            break;
          case R.id.repairshop_comment_hardware:
            ((TextView)findViewById(R.id.repairshop_comment_hardware_sum)).setText(arg0.result.toString()+"%");
            break;

          default:
            break;
          }
        } catch (Exception e) {
          LogUtils.e("error:"+arg0.result.toString());
          progressBar.setProgress(0);
        }
      }
    });
  }
  
  @OnRadioGroupCheckedChange(R.id.repairshop_comment_group)
  public void onCommentCheckedChanged(RadioGroup arg0, int arg1) {
    switch (arg1) {
    case R.id.repairshop_comment_goog_g:
      score = "0";
      break;
    case R.id.repairshop_comment_goog_m:
      score = "1";
      break;
    case R.id.repairshop_comment_goog_b:
      score = "2";
      break;
    default:
      score=null;
      break;
    }
    addCommentData = false;
    commentListAdapter.clear();
    commentPager.reset();
    commentPager.getRepairShopComment(rid, score, callbackRefreshCommentList);
  }

  private IXListViewListener onCommentViewListener = new IXListViewListener() {
    @Override
    public void onRefresh() {
      addCommentData = false;
      commentListAdapter.clear();
      commentPager.reset();
      commentList.getmFooterView().setState(XListViewFooter.STATE_NORMAL);
      commentPager.getRepairShopComment(rid, score, callbackRefreshCommentList);
    }

    @Override
    public void onLoadMore() {
      addCommentData = true;
      commentPager.getRepairShopComment(rid, score, callbackRefreshCommentList);
    }
  };
  
  /**
   * 停止刷新，
   */
  private void onStopLoad() {
    commentList.stopRefresh();
    commentList.stopLoadMore();
    commentList.setRefreshTime("刚刚");
  }
  
  /**
   * 收藏按钮事件 文件 cn.car91.activity.RepairShopMainActivity.java
   *
   * @author 周海刚 时间 2014年11月25日
   */
  private class CollectionBtnClickEvent {
    private String rid;

    public void setRid(String rid) {
      this.rid = rid;
    }

    public CollectionBtnClickEvent() {
      super();
    }

    public OnClickListener onClickListener = new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        // TODO Auto-generated method stub
        if (RegexUtil.isNotNull(rid)) {
          if (getCar91Application().getUser() == null) {
            HerilyAlertDialog.Builder builder = new HerilyAlertDialog.Builder(
                RepairShopDetailActivity.this);
            // builder.setIcon(R.drawable.icon);
            builder.setMessage("请先登录");
            builder.setPositiveButton("登录",
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                    // 这里添加点击确定后的逻辑
                    Intent intent = new Intent();
                    intent.setClass(RepairShopDetailActivity.this,
                        UserLoginActivity.class);
                    startActivityForResult(intent, Request_Code);
                  }
                });
            builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                  }
                });
            builder.create().show();
          } else {
            if (hadCollection)
              HttpHandler.httpHandler.repairShopCollect(rid,
                  getCar91Application().getUser().getId(), "d",
                  callbackCollection);
            else
              HttpHandler.httpHandler.repairShopCollect(rid,
                  getCar91Application().getUser().getId(), "a",
                  callbackCollection);
          }
        }
      }
    };
  }
  
  private class MapClickEvent {
    private Double Lon;
    private Double Lat;
    private RepairShop repairShop;

    public MapClickEvent(Double Lon, Double Lat, RepairShop repairShop) {
      this.Lon = Lon;
      this.Lat = Lat;
      this.repairShop = repairShop;
    }

    public OnClickListener onClickListener = new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        try {
          if (Lat != null && Lon != null) {
            Intent intent = new Intent();
            intent.putExtra("lon", Lon);
            intent.putExtra("lat", Lat);
            intent.putExtra("name", repairShopDetailHandler.repairShopName
                .getText().toString());
            intent.putExtra("repairshop", (Serializable) repairShop);
            intent.setClass(RepairShopDetailActivity.this, MapActivity.class);
            startActivity(intent);
          }
        } catch (Exception e) {
          // TODO: handle exception
        }
      }
    };
  }

  /**
   * html获取本地图片资源
   */
  ImageGetter imgGetter = new ImageGetter() {
    @Override
    public Drawable getDrawable(String source) {
      // TODO Auto-generated method stub
      int id = Integer.parseInt(source);
      Drawable d = getResources().getDrawable(id);
      d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
      return d;
    }
  };

  /**
   * 回调获取商家详情
   */
  private RequestCallBack callbackDetail = new RequestCallBack() {

    @Override
    public void onStart() {
      // TODO Auto-generated method stub
      super.onStart();
      if (dialog != null)
        if (!dialog.isShowing())
          dialog.show();
    }

    @Override
    public void onFailure(HttpException arg0, String arg1) {
      // TODO Auto-generated method stub
      Toast.makeText(getApplicationContext(), "网络不给力啊~", Toast.LENGTH_SHORT)
          .show();
    }

    @Override
    public void onSuccess(ResponseInfo arg0) {
      // TODO Auto-generated method stub
      if (dialog != null)
        if (dialog.isShowing())
          dialog.cancel();
      initData((RepairShop) Car91JsonUtil.getDTO(arg0.result.toString(),
          RepairShop.class));
    }
  };
  
  String descContent;
  @OnClick(R.id.repairshop_detail_desc)
  public void onDescClick(View view) {
    Intent intent = new Intent(this, RepairShopDescActivity.class);
    intent.putExtra("repairshop_name", rname);
    intent.putExtra("repairshop_desc", descContent);
    startActivity(intent);
  }
  String creditUrl;
  @OnClick(R.id.repairshop_detail_credit)
  public void onCreditClick(View view) {
    Intent intent = new Intent(this, RepairShopCreditActivity.class);
    intent.putExtra("repairshop_name", rname);
    intent.putExtra("repairshop_credit", creditUrl);
    startActivity(intent);
  }
  ArrayList<String> allTechs=new ArrayList<String>();
  ArrayList<String> allHards=new ArrayList<String>();
  @OnClick(R.id.repairshop_detail_technical)
  public void onTechnicalClick(View view) {
    Intent intent = new Intent(this, RepairShopHardTechActivity.class);
    intent.putExtra("repairshop_name", rname);
    intent.putStringArrayListExtra("repairshop_technology", allTechs);
    intent.putStringArrayListExtra("repairshop_hardware", allHards);
    startActivity(intent);
  }
  

  /* 留言 */
  boolean addCommentData = false;
  private RequestCallBack callbackRefreshCommentList = new RequestCallBack() {

    @Override
    public void onFailure(HttpException arg0, String arg1) {
      // TODO Auto-generated method stub
    }

    @Override
    public void onSuccess(ResponseInfo arg0) {
      // TODO Auto-generated method stub
      onStopLoad();
      try {
        List<RepairShopComment> comments = Car91JsonUtil.getDTOList(
            arg0.result.toString(), RepairShopComment.class);
        if(addCommentData) {
          if(comments.size()>0) {
            commentListAdapter.addData(comments);
          } else {
            commentList
            .getmFooterView().setState(XListViewFooter.STATE_NOMORE);
          }
        } else {
          commentListAdapter.setData(comments);
          if(!(comments.size()>0)) {
            commentList
            .getmFooterView().setState(XListViewFooter.STATE_NOMORE);
          }
        }
        commentListAdapter.notifyDataSetChanged();
      } catch (Exception e) {}
    }
  };

  private RequestCallBack callbackCollection = new RequestCallBack() {

    @Override
    public void onFailure(HttpException arg0, String arg1) {
      // TODO Auto-generated method stub
      Toast.makeText(getApplicationContext(), "网络异常，请稍后再试", Toast.LENGTH_LONG)
          .show();
    }

    @Override
    public void onSuccess(ResponseInfo arg0) {
      // TODO Auto-generated method stub
      Integer state = Integer.valueOf(arg0.result.toString());

      if (state != null) {
        Drawable drawable = null;
        switch (state) {
        case 1:
          hadCollection = true;
          Toast.makeText(getApplicationContext(), "收藏成功", Toast.LENGTH_SHORT)
              .show();
          drawable = getResources().getDrawable(R.drawable.collection_had);
          break;
        case 11:
          hadCollection = false;
          Toast.makeText(getApplicationContext(), "已取消收藏", Toast.LENGTH_SHORT)
              .show();
          drawable = getResources().getDrawable(R.drawable.collection_none);
          break;
        default:
          Toast.makeText(getApplicationContext(), "收藏失败", Toast.LENGTH_SHORT)
              .show();
          break;
        }
        if (drawable != null) {
          drawable.setBounds(0, 0, drawable.getMinimumWidth(),
              drawable.getMinimumHeight());
          repaircollectionBtn.setCompoundDrawables(null, drawable, null, null);
        }
      }
    }
  };

  private void checkCollection() {
    User user = getCar91Application().getUser();
    if (user != null && RegexUtil.isNotNull(rid)) {
      HttpHandler.httpHandler.checkRepairShopCollect(rid, user.getId(),
          callbackCheckCollection);
    }
  }

  private RequestCallBack callbackCheckCollection = new RequestCallBack() {

    @Override
    public void onFailure(HttpException arg0, String arg1) {
      // TODO Auto-generated method stub

    }

    @Override
    public void onSuccess(ResponseInfo arg0) {
      // TODO Auto-generated method stub
      Integer state = Integer.valueOf(arg0.result.toString());
      if (state != null) {
        Drawable drawable = null;
        switch (state) {
        case 1:
          hadCollection = true;
          drawable = getResources().getDrawable(R.drawable.collection_had);
          break;
        default:
          hadCollection = false;
          drawable = getResources().getDrawable(R.drawable.collection_none);
          break;
        }
        if (drawable != null) {
          drawable.setBounds(0, 0, drawable.getMinimumWidth(),
              drawable.getMinimumHeight());
          // collectionBtn.setCompoundDrawables(null, drawable, null,
          // null);
        }
      }
    }
  };

  // 拨号
  private OnClickListener onCallClickListener = new OnClickListener() {
    @Override
    public void onClick(View arg0) {
      // TODO Auto-generated method stub
      if (repairShopDetailHandler != null) {
        MobileOperationUtil.callPhone(RepairShopDetailActivity.this, phoneNum);
      }
    }
  };

  // 留言评论
  private OnClickListener onCommentClickListener = new OnClickListener() {

    @Override
    public void onClick(View arg0) {
      // TODO Auto-generated method stub
      if (RegexUtil.isNotNull(rid)) {
        if (getCar91Application().getUser() != null) {
          Intent intent = new Intent();
          intent.setClass(RepairShopDetailActivity.this,
              RepairShopCommentActivity.class);
          intent.putExtra("rname", rname);
          intent.putExtra("rid", rid);
          startActivityForResult(intent, Request_Code);
        } else {
          HerilyAlertDialog.Builder builder = new HerilyAlertDialog.Builder(
              RepairShopDetailActivity.this);
          // builder.setIcon(R.drawable.icon);
          builder.setMessage("请先登录");
          builder.setPositiveButton("登录",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                  // 这里添加点击确定后的逻辑
                  Intent intent = new Intent();
                  intent.setClass(RepairShopDetailActivity.this,
                      UserLoginActivity.class);
                  startActivityForResult(intent,
                      Car91ResultCode.Refresh_User_Code);
                }
              });
          builder.setNegativeButton("取消",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
              });
          builder.create().show();
        }
      }
    }
  };

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    // Toast.makeText(RepairShopDetailActivity.this,
    // "request:"+requestCode+" result:"+resultCode+" init:"+Request_Code,
    // Toast.LENGTH_LONG).show();
    if (requestCode == Request_Code) {
      switch (resultCode) {
      case Car91ResultCode.Refresh_User_Code:
        checkCollection();
        break;
      default:
        break;
      }
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
